package qc.module.qms.service.exchange;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.module.qms.dto.exchange.channel.ExchangeChannelDto;
import qc.module.qms.entity.ExchangeCategory;
import qc.module.qms.entity.ExchangeChannel;
import qc.module.qms.mapper.ExchangeChannelMapper;
import qc.module.qms.repository.ExchangeChannelRepository;

import java.util.List;
import java.util.Objects;

/**
 * ExchangeChannelService
 *
 * @author QuCheng Tech
 * @since 2024/1/23
 */
@Service
public class ExchangeChannelService {
    private ExchangeChannelRepository repository;
    
    @Autowired
    private ExchangeCategoryService categoryService;

    @Autowired
    public void setExchangeChannelRepository(ExchangeChannelRepository repository) {
        this.repository = repository;
    }

    /***
     * 获取所有通道信息
     *
     * @return java.util.List<qc.module.qms.dto.exchange.channel.ExchangeChannelDto>
     * @author QuCheng Tech
     * @since 2024/1/24
     */
    public List<ExchangeChannelDto> getAll() {
        LambdaQueryWrapper<ExchangeChannel> wrapper = new LambdaQueryWrapper<>();

        //排序，按通道名称升序
        wrapper.orderByAsc(ExchangeChannel::getName);

        //查询数据
        List<ExchangeChannel> ens = repository.selectList(wrapper);
        if (ens != null && ens.size() > 0x0) {
            return ExchangeChannelMapper.MAPPER.toDtoList(ens);
        }

        return null;
    }

    /***
     * 获取指定通道ID集合的通道信息列表
     *
     * @param channelIds 通道ID集合
     * @return java.util.List<qc.module.qms.dto.exchange.channel.ExchangeChannelDto>
     * @author QuCheng Tech
     * @since 2024/1/24
     */
    public List<ExchangeChannelDto> getByFilterIds(Integer[] channelIds) {
        //如果传入的通道ID集合为空，返回结果为空
        if (channelIds != null && channelIds.length > 0x0) {
            LambdaQueryWrapper<ExchangeChannel> wrapper = new LambdaQueryWrapper<>();

            //根据ID进行筛选
            //优化查询条件：如果通道ID集合只有1个使用eq条件
            if (channelIds.length == 0x1)
                wrapper.eq(ExchangeChannel::getId, channelIds[0x0]);
            else
                wrapper.in(ExchangeChannel::getId, channelIds);

            //排序，按通道名称升序
            wrapper.orderByAsc(ExchangeChannel::getName);

            //查询数据
            List<ExchangeChannel> ens = repository.selectList(wrapper);
            if (ens != null && ens.size() > 0x0) {
                return ExchangeChannelMapper.MAPPER.toDtoList(ens);
            }
        }

        return null;
    }

    /***
     * 根据指定的数据分类ID集合查询通道集合信息
     *
     * @param categoryIds 数据分类ID集合 
     * @return java.util.List<qc.module.qms.dto.exchange.channel.ExchangeChannelDto>
     * @author QuCheng Tech
     * @since 2024/1/24
     */
    public List<ExchangeChannelDto> getByCategoryIds(Integer[] categoryIds) {
        //如果传入的分类ID集合为空，返回结果为空
        if (categoryIds != null && categoryIds.length > 0x0) {
            MPJLambdaWrapper<ExchangeChannel> wrapper = new MPJLambdaWrapper<>();
            wrapper.select(ExchangeChannel::getId, ExchangeChannel::getName, ExchangeChannel::getComtype, ExchangeChannel::getDirection);
            wrapper.innerJoin(ExchangeCategory.class, ExchangeCategory::getCid, ExchangeChannel::getId);
            wrapper.in(ExchangeCategory::getId, categoryIds);

            //排序，按通道名称升序
            wrapper.orderByAsc(ExchangeChannel::getName);

            //查询数据
            List<ExchangeChannel> ens = repository.selectJoinList(ExchangeChannel.class, wrapper);
            if (ens != null && ens.size() > 0x0) {
                return ExchangeChannelMapper.MAPPER.toDtoList(ens);
            }
        }

        return null;
    }

    /***
     * 获取指定通道ID的通道信息
     *
     * @param channelId 通道ID
     * @return qc.module.qms.dto.exchange.channel.ExchangeChannelDto
     * @author QuCheng Tech
     * @since 2024/1/24
     */
    public ExchangeChannelDto get(int channelId) {
        ExchangeChannel en = repository.selectById(channelId);

        if (en != null)
            return ExchangeChannelMapper.MAPPER.toDto(en);

        return null;
    }
    
    /**
     * 新增
     *
     * @return 成功返回null，失败返回错误信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    public String add(ExchangeChannelDto dto){
        if (Objects.isNull(dto)) return QCUnifyReturnValue.Warn("查询对象不能为空");
        if (StringUtils.isBlank(dto.getName())) return QCUnifyReturnValue.Warn("通道名称不能为空");
        
        ExchangeChannel en = ExchangeChannelMapper.MAPPER.dtoToEntity(dto);

        en.setId(generateId());

        if (repository.insert(en) < 0x1)
            return QCUnifyReturnValue.Warn("新增数据失败");
        return QCUnifyReturnValue.Success();
    }

    /**
     * 修改
     *
     * @return 成功返回null，失败返回错误信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    public String update(ExchangeChannelDto dto){
        if (Objects.isNull(dto)) return QCUnifyReturnValue.Warn("查询对象不能为空");
        if (StringUtils.isBlank(dto.getName())) return QCUnifyReturnValue.Warn("通道名称不能为空");

        if (!isExist(dto.getId())){
            return QCUnifyReturnValue.Warn("修改的通道信息不存在");
        }
        
        ExchangeChannel en = ExchangeChannelMapper.MAPPER.dtoToEntity(dto);

        repository.updateById(en);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 删除
     *
     * @param channelId 交换通道ID
     * @return 成功返回null，失败返回错误信息
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    public String delete(Integer channelId) throws QCPromptException {
        // 1.条件判空
        if (channelId < 0x1)
            throw new QCPromptException("交换通道ID不能为空");
        
        //2.判断通道ID下是否有数据分类，如果有则提示
        if (CollectionUtils.isNotEmpty(categoryService.getByChannelId(channelId))){
            throw new QCPromptException("此交换通道ID下有数据分类信息，请先删除数据分类信息");
        }
        
        repository.deleteById(channelId);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 判断对象是否存在
     * @param id 通道ID
     * @return 返回true表示存在，false表示不存在
     * @author QuCheng Tech
     * @since 2024/4/16
     */
    public boolean isExist(Integer id){
        if (Objects.nonNull(repository.selectById(id)))
            return true;
        return false;
    }

    /**
     * 生成记录ID，获取数据库表中的最大记录ID+1
     *
     * @return 生成记录ID
     * @author QuCheng Tech
     * @since 2023/5/28
     */
    Integer generateId() {
        Integer maxRecordId = getMaxId();
        return maxRecordId + 1;
    }

    /**
     * 获取数据库表中的最大ID值，没有记录时返回0
     *
     * @return 返回数据库表中的最大ID值
     * @author QuCheng Tech
     * @since 2023/5/28
     */
    Integer getMaxId() {
        LambdaQueryWrapper<ExchangeChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ExchangeChannel::getId)
                .orderByDesc(ExchangeChannel::getId);

        ExchangeChannel en = repository.selectOne(wrapper);
        if (en != null)
            return en.getId();

        return 0x0;
    }
}
